import { Login } from "@/api/users.js";
import { getMenu } from "@/api/menu.js";
import { ACCESS_TOKEN, USERINFO, PICT } from "@/store/mutation_types";
import Vue from "vue";
const state = {
  token: '',
  userinfo: {},
  permissions: [],
  headPict: '',
  bgPict: '',
}
// 对state里面的变量进行过滤的
const getters = {
  token: state => state.token,
  userinfo: state => state.userinfo,
  headPict: state => { state.headPict = Vue.ls.get(PICT); return state.headPict; }
}
const mutations = {
  SET_TOKEN(state, val) {
    state.token = val
  },
  SET_USERINFO(state, val) {
    state.userinfo = Object.assign({}, val)
  },
  SET_PERMISSION(state, val) {
    state.permissions = JSON.parse(JSON.stringify(val))
  },
  SET_HEADPICT(state, val) {
    state.headPict = val
  },
  SET_BGPICT(state, val) {
    state.bgPict = val
  },
}
const actions = {
  LoginIn({ commit }, userinfo) {
    return new Promise((resolve, reject) => {
      Login(userinfo).then(res => {
        console.log(res);
        if (res.success) {
          let info = res.data;
          let userinfo = { id: info.id, phone: info.phone, username: info.username };
          Vue.ls.set(ACCESS_TOKEN, info.token, 7 * 24 * 60 * 60 * 1000)
          Vue.ls.set(USERINFO, userinfo, 7 * 24 * 60 * 60 * 1000);
          commit('SET_TOKEN', info.token);
          commit('SET_USERINFO', userinfo);
          resolve(res)
        } else {
          reject(res)
        }
      })
    })
  },
  getMenuList({ commit }, name) {
    return new Promise((resolve, reject) => {
      getMenu(name).then(res => {
        if (res.success) {
          commit('SET_PERMISSION', res.data);
          resolve(res)
        } else {
          reject(res)
        }
      })
    })
  },
}
export default {
  state,
  getters,
  mutations,
  actions
}